package mint2tcp;

import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.control.cell.PropertyValueFactory;

public class MainController {

    @FXML private ComboBox<String> modeComboBox;
    @FXML private TextField ipField;
    @FXML private TextField portField;
    @FXML private Button connectButton;
    @FXML private Button disconnectButton;
    @FXML private Button clearButton;
    @FXML private Label statusLabel;
    @FXML private TableView<mint2tcp.DataParser.DataPoint> dataTable;
    @FXML private TableColumn<mint2tcp.DataParser.DataPoint, Double> latColumn;
    @FXML private TableColumn<mint2tcp.DataParser.DataPoint, Double> lonColumn;
    @FXML private TableColumn<mint2tcp.DataParser.DataPoint, Double> heightColumn;
    @FXML private TableColumn<mint2tcp.DataParser.DataPoint, Double> rainfallColumn; // 新增：降雨量列
    @FXML private TextArea responseArea;

    private ObservableList<mint2tcp.DataParser.DataPoint> dataPoints = FXCollections.observableArrayList();
    private double totalCumulativeRainfall = 0; // 累计降雨量

    private TcpClient tcpClient;
    private TcpServer tcpServer;
    private Thread clientThread;
    private Thread serverThread;

    @FXML
    public void initialize() {
        modeComboBox.setItems(FXCollections.observableArrayList("Client", "Server"));
        modeComboBox.getSelectionModel().selectFirst();

        // 设置 TableView 列
        latColumn.setCellValueFactory(new PropertyValueFactory<>("latitude"));
        lonColumn.setCellValueFactory(new PropertyValueFactory<>("longitude"));
        heightColumn.setCellValueFactory(new PropertyValueFactory<>("height"));
        rainfallColumn.setCellValueFactory(new PropertyValueFactory<>("rainfall")); // 新增：降雨量列
        dataTable.setItems(dataPoints);

        connectButton.setDisable(false);
        disconnectButton.setDisable(true);
        statusLabel.setText("状态：未连接");
        statusLabel.setStyle("-fx-text-fill: red;");

        modeComboBox.setOnAction(event -> updateUIForMode());
    }

    @FXML
    public void start(ActionEvent event) {
        String mode = modeComboBox.getSelectionModel().getSelectedItem();
        if (mode == null) {
            showAlert("Mode Error", "Please select a mode (Client or Server).");
            return;
        }

        String ip = ipField.getText();
        int port;
        try {
            port = Integer.parseInt(portField.getText());
        } catch (NumberFormatException e) {
            showAlert("Invalid Port", "Please enter a valid port number.");
            return;
        }

        connectButton.setDisable(true);
        disconnectButton.setDisable(false);

        if (mode.equals("Client")) {
            startClient(ip, port);
        } else {
            startServer(port);
        }
    }

    @FXML
    public void stop(ActionEvent event) {
        if (tcpClient != null) {
            tcpClient.disconnect();
            tcpClient = null;
        }
        if (clientThread != null) {
            clientThread.interrupt();
            clientThread = null;
        }

        connectButton.setDisable(false);
        disconnectButton.setDisable(true);
        setStatus("状态：未连接", "red");
    }

    @FXML
    public void clearMessages(ActionEvent event) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认清空");
        alert.setHeaderText(null);
        alert.setContentText("确定要清空消息吗？");

        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                responseArea.clear();
            }
        });
    }

    private void startClient(String ip, int port) {
        tcpClient = new TcpClient(ip, port);
        tcpClient.setController(this);
        clientThread = new Thread(tcpClient);
        clientThread.start();
    }

    private void startServer(int port) {
        tcpServer = new TcpServer(port);
        tcpServer.setController(this);
        serverThread = new Thread(tcpServer);
        serverThread.start();
    }

    public void updateUIForMode() {
        String mode = modeComboBox.getSelectionModel().getSelectedItem();
        if (mode != null && mode.equals("Server")) {
            ipField.setDisable(true);
            ipField.setText("127.0.0.1");
        } else {
            ipField.setDisable(false);
        }
    }

    public void appendResponse(String msg) {
        if (responseArea != null) {
            // 解析消息，提取降雨量
            if (msg.contains("PULSES")) {
                String[] parts = msg.split(",");
                if (parts.length > 3) {
                    double pulses = Double.parseDouble(parts[3]);
                    double rainfall = pulses * 0.1; // 每脉冲 0.1mm
                    totalCumulativeRainfall += rainfall;
                    responseArea.appendText("降雨量: " + rainfall + " mm, 累计降雨量: " + totalCumulativeRainfall + " mm\n");
                }
            } else {
                responseArea.appendText(msg);
            }
        }
    }

    public void setStatus(String msg, String color) {
        statusLabel.setText(msg);
        statusLabel.setStyle("-fx-text-fill: " + color + ";");
    }

    public void addDataPoint(mint2tcp.DataParser.DataPoint dataPoint) {
        dataPoints.add(dataPoint);
        // 更新累计降雨量
        totalCumulativeRainfall += dataPoint.getRainfall();
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}